package controller.addtextServlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import bean.Filesf;
import dao.util.FilesCreate;
import bean.User;

import java.io.IOException;
import java.util.List;

@WebServlet("/mynote/View")
public class View extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String filename = request.getParameter("filename");
        User currentUser = null;
        if (request.getSession(false) != null) {
            currentUser = (User) request.getSession(false).getAttribute("user");
        }
        int userId = currentUser != null ? currentUser.getId() : -1;
        FilesCreate filesCreate = new FilesCreate();
        List<Filesf> filesfs = filesCreate.getMapperClass().selectFilesByName(filename, userId);
        filesCreate.closesession();

        if (filesfs != null && !filesfs.isEmpty()) {
            Filesf file = filesfs.get(0); // 取第一个文件（通常是唯一的）

            // 设置 MIME 类型（例如 image/jpeg, application/pdf 等）
            response.setContentType(file.getFiletype());

            // 👉 如果要强制下载，启用这一行
            // response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getFilename(), "UTF-8"));

            // 输出文件数据
            response.getOutputStream().write(file.getFiledata());
            response.getOutputStream().flush();

        } else {
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("文件不存在: " + filename);
        }
    }
}
